using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using AnyThinkAds.Api;
using AnyThinkAds.ThirdParty.LitJson;

public class HomeScreenScene : MonoBehaviour, ATSDKInitListener, ATConsentDismissListener {
#if UNITY_ANDROID
    private const string SdkAppId = "h66bdaad27dac1";
    private const string SdkKey = "afaa8fe06949bde524939c7f29a18332d";
#elif UNITY_IOS || UNITY_IPHONE
    private const string SdkAppId = "h66bdaa18ec68d";
    private const string SdkKey = "a159f9696c846c9edb9e616b4bee520bc";
#endif

    public Button showInterstitialButton;
    public Button showRewardButton;
    public Button showSplashButton;
    public Button showBannerButton;
    public Button showNativeButton;
    public Button mediationDebuggerButton;
    public Button automicRewardInterButton;
    public Text interstitialStatusText;
    public Text rewardStatusText;
    public Text splashStatusText;
    public Text nativeStatusText;
    public Text bannerStatusText;

    private bool _isBannerAdShowing; // 是否显示Banner
    private bool _isNativeAdShowing; // 是否显示Native

    // Start is called before the first frame update
    void Start() {
        Debug.Log("wcx Start() >>> ");
        // 对应的按钮点击事件
        showInterstitialButton.onClick.AddListener(ShowInterstitialAd);
        showRewardButton.onClick.AddListener(ShowRewardedAd);
        showSplashButton.onClick.AddListener(ShowSplashAd);
        showBannerButton.onClick.AddListener(ShowBannerAd); // 显示/隐藏Banner
        showNativeButton.onClick.AddListener(ShowNativeAd);
        mediationDebuggerButton.onClick.AddListener(OpenDebuggerUITool);
        automicRewardInterButton.onClick.AddListener(JumpToAutomicPage);
        // 初始化SDK
        //读取存档判断是否展示过GDPR授权弹窗
        if (PlayerPrefs.GetInt("isShowGDPRAuth") == 0) {
            Debug.Log("wcx isShowGDPRAuth == 0");
            ATSDKAPI.showGDPRConsentDialog(this);
        }
        else {
            Debug.Log("wcx isShowGDPRAuth == 1");
            InitializeSDK();
        }
    }

    void OnDestroy() {
        InterstitialAdOperator.Instance.destroyAd();
        RewardVideoAdOperator.Instance.destroyAd();
        SplashAdOperator.Instance.destroyAd();
        BannerAdOperator.Instance.destroyAd();
        NativeAdOperator.Instance.destroyAd();
    }

    private void OpenDebuggerUITool() {
        // ATSDKAPI.showDebuggerUI();

        // DebuggerUI Tools supports online ad placement testing starting from version 1.0.8.
        // "abbfb0a2699ff81561f6905a5c8585275fc166c4" is a Debug Key, used for online ID testing. You can get it from Backstage -> Account Management -> Key
        ATSDKAPI.showDebuggerUI("abbfb0a2699ff81561f6905a5c8585275fc166c4");
    }

    private void JumpToAutomicPage() {
        SceneManager.LoadScene("AutomicRewardInterScene");
    }

    private void InitializeSDK() {
        Debug.Log("wcx SDK Start InitializeSdk");
        Debug.Log("wcx UnityVersion of the runtime: " + Application.unityVersion);
        Debug.Log("wcx Device Screen size : {" + Screen.width + ", " + Screen.height + "}");

        //（可选配置）设置自定义的Map信息，可匹配后台配置的广告商顺序的列表（App纬度）
        //注意：调用此方法会清除setChannel()、setSubChannel()方法设置的信息，如果有设置这些信息，请在调用此方法后重新设置
        ATSDKAPI.initCustomMap(new Dictionary<string, string> { { "unity3d_data", "test_data" } });
        //（可选配置）设置自定义的Map信息，可匹配后台配置的广告商顺序的列表（Placement纬度）
        ATSDKAPI.setCustomDataForPlacementID(new Dictionary<string, string> { { "unity3d_data_pl", "test_data_pl" } },
            "b5b728e7a08cd4"); // TODO 这个key是从哪里来的?
        //（可选配置）设置渠道的信息，开发者可以通过该渠道信息在后台来区分看各个渠道的广告数据
        // 注意：如果有使用initCustomMap()方法，必须在initCustomMap()方法之后调用此方法
        ATSDKAPI.setChannel("unity3d_test_channel"); // 渠道
        //（可选配置）设置子渠道的信息，开发者可以通过该渠道信息在后台来区分看各个渠道的子渠道广告数据
        // 注意：如果有使用initCustomMap()方法，必须在initCustomMap()方法之后调用此方法
        ATSDKAPI.setSubChannel("unity3d_test_Subchannel"); // 子渠道

        //设置开启Debug日志（强烈建议测试阶段开启，方便排查问题）
        ATSDKAPI.setLogDebug(true);

        Debug.Log("wcx Developer DataConsent: " + ATSDKAPI.getGDPRLevel()); // 获取GDPR状态
        Debug.Log("wcx Developer isEUTrafic: " + ATSDKAPI.isEUTraffic()); // 是否是欧盟流量
        ATSDKAPI.getUserLocation(new GetLocationListener()); // 获取用户位置信息

        //Only for Android China SDK (CSJ) --- 中国区的sdk!!!!
#if UNITY_ANDROID
        ATDownloadManager.Instance.setListener(new ATDownloadListener()); // 设置下载监听
#endif
        //（必须配置）SDK的初始化
        ATSDKAPI.initSDK(SdkAppId, SdkKey, this);
    }

    public void onConsentDismiss() {
        Debug.Log("wcx onConsentDismiss >>> ");
        PlayerPrefs.SetInt("isShowGDPRAuth", 1);
        InitializeSDK();
    }

    //This method will be called back after the SDK is initialized successfully
    public void initSuccess() {
        Debug.Log("wcx Developer callback SDK initSuccess");
        if (InitSdkHelper.IsInited) {
            Debug.Log("wcx Developer callback SDK initSuccess, already inited");
            return;
        }

        InitSdkHelper.IsInited = true; // 防止重复初始化
        InitializeInterstitialAds(); // 初始化插屏广告
        InitializeRewardedAds(); // 初始化激励视频广告
        InitializeBannerAds(); // 初始化Banner广告

        // InitializeNativeAds(); // 初始化原生广告---不支持
        // InitializeSplashAds(); // 初始化开屏广告
        //Splash ads display directly
        // ShowSplashAd(); // 显示开屏广告
    }

    //This method will be called back after the SDK is initialized failed
    public void initFail(string msg) {
        Debug.Log("wcx Developer callback SDK initFail:" + msg);
    }

    private void InitializeInterstitialAds() { // 初始化插屏广告
        InterstitialAdOperator.Instance.statusChangeEvent += statusChange;
        InterstitialAdOperator.Instance.retryLoadAdAttemptEvent += retryLoadAdAttempt;
        InterstitialAdOperator.Instance.initializeAd();
        LoadInterstitialAd();
    }

    private void InitializeRewardedAds() { // 初始化激励视频广告
        RewardVideoAdOperator.Instance.statusChangeEvent += statusChange;
        RewardVideoAdOperator.Instance.retryLoadAdAttemptEvent += retryLoadAdAttempt;
        RewardVideoAdOperator.Instance.initializeAd();
        LoadRewardVideoAd();
    }

    private void InitializeSplashAds() {
        SplashAdOperator.Instance.statusChangeEvent += statusChange;
        SplashAdOperator.Instance.retryLoadAdAttemptEvent += retryLoadAdAttempt;
        SplashAdOperator.Instance.initializeAd();
        LoadSplashAd();
    }

    private void InitializeBannerAds() {
        BannerAdOperator.Instance.statusChangeEvent += statusChange;
        BannerAdOperator.Instance.retryLoadAdAttemptEvent += retryLoadAdAttempt;
        BannerAdOperator.Instance.initializeAd();
        LoadBannerAd();
    }

    private void InitializeNativeAds() {
        NativeAdOperator.Instance.statusChangeEvent += statusChange;
        NativeAdOperator.Instance.retryLoadAdAttemptEvent += retryLoadAdAttempt;
        NativeAdOperator.Instance.initializeAd();
        LoadNativeAd();
    }

    public void ShowInterstitialAd() {
        // 显示插屏广告
        InterstitialAdOperator.Instance.showAd();
    }

    public void ShowRewardedAd() {
        // 显示激励视频广告
        RewardVideoAdOperator.Instance.showAd();
    }

    public void ShowSplashAd() {
        // 显示开屏广告
        SplashAdOperator.Instance.showAd();
    }

    public void ShowBannerAd() {
        // 显示/隐藏Banner
        if (!_isBannerAdShowing) {
            BannerAdOperator.Instance.showAd();
            showBannerButton.GetComponentInChildren<Text>().text = "Hide Banner";
        }
        else {
            BannerAdOperator.Instance.hideBannerAd();
            showBannerButton.GetComponentInChildren<Text>().text = "Show Banner";
        }

        _isBannerAdShowing = !_isBannerAdShowing;
    }

    public void ShowNativeAd() {
        if (!_isNativeAdShowing) {
            NativeAdOperator.Instance.showAd();
            showNativeButton.GetComponentInChildren<Text>().text = "Hide Native";
        }
        else {
            NativeAdOperator.Instance.cleanAdView();
            showNativeButton.GetComponentInChildren<Text>().text = "Show Native";
        }

        _isNativeAdShowing = !_isNativeAdShowing;
    }

    public void showGDPRAuth() {
        Debug.Log("wcx Developer showGDPRAuth");

        ATSDKAPI.showGDPRAuth();
    }

    public void LoadInterstitialAd() {
        Debug.Log("wcx LoadInterstitialAd() >>> ");
        InterstitialAdOperator.Instance.loadAd();
    }

    public void LoadRewardVideoAd() {
        RewardVideoAdOperator.Instance.loadAd();
    }

    public void LoadSplashAd() {
        SplashAdOperator.Instance.loadAd();
    }

    public void LoadBannerAd() {
        BannerAdOperator.Instance.loadAd();
    }

    public void LoadNativeAd() {
        NativeAdOperator.Instance.loadAd();
    }

    public void statusChange(object selfer, string status) {
        Debug.Log("wcx statusChange() >>> selfer: " + selfer + " status: " + status);
        if (Object.ReferenceEquals(selfer, InterstitialAdOperator.Instance)) {
            interstitialStatusText.text = status;
        }
        else if (Object.ReferenceEquals(selfer, RewardVideoAdOperator.Instance)) {
            rewardStatusText.text = status;
        }
        else if (Object.ReferenceEquals(selfer, SplashAdOperator.Instance)) {
            splashStatusText.text = status;
        }
        else if (Object.ReferenceEquals(selfer, BannerAdOperator.Instance)) {
            bannerStatusText.text = status;
        }
        else if (Object.ReferenceEquals(selfer, NativeAdOperator.Instance)) {
            nativeStatusText.text = status;
        }
    }

    public void retryLoadAdAttempt(object selfer, float retryDelay) {
        Debug.Log("wcx retryLoadAdAttempt() >>> selfer: " + selfer + " retryDelay: " + retryDelay);
        if (Object.ReferenceEquals(selfer, InterstitialAdOperator.Instance)) {
            Invoke("LoadInterstitialAd", retryDelay);
        }
        else if (Object.ReferenceEquals(selfer, RewardVideoAdOperator.Instance)) {
            Invoke("LoadRewardVideoAd", retryDelay);
        }
        else if (Object.ReferenceEquals(selfer, SplashAdOperator.Instance)) {
            Invoke("LoadSplashAd", retryDelay);
        }
        else if (Object.ReferenceEquals(selfer, BannerAdOperator.Instance)) {
            Invoke("LoadBannerAd", retryDelay);
        }
        else if (Object.ReferenceEquals(selfer, NativeAdOperator.Instance)) {
            Invoke("LoadNativeAd", retryDelay);
        }
    }

    private class GetLocationListener : ATGetUserLocationListener {
        // 获取用户位置信息
        public void didGetUserLocation(int location) {
            Debug.Log("wcx Developer callback didGetUserLocation(): " + location);
            if (location == ATSDKAPI.kATUserLocationInEU && ATSDKAPI.getGDPRLevel() == ATSDKAPI.UNKNOWN) {
                ATSDKAPI.showGDPRAuth();
            }
        }
    }

    //Only for Android China SDK (Pangle)
    class ATDownloadListener : ATDownloadAdListener {
        public void onDownloadFail(string placementId, ATCallbackInfo callbackInfo, long totalBytes, long currBytes,
            string fileName, string appName) {
            Debug.Log("wcx Developer onDownloadFail------->" + JsonMapper.ToJson(callbackInfo.toDictionary())
                                                             + "\n, totalBytes: " + totalBytes + ", currBytes:" +
                                                             currBytes
                                                             + "\n, fileName: " + fileName + ", appName: " + appName);
        }

        public void onDownloadFinish(string placementId, ATCallbackInfo callbackInfo, long totalBytes, string fileName,
            string appName) {
            Debug.Log("wcx Developer onDownloadFinish------->" + JsonMapper.ToJson(callbackInfo.toDictionary())
                                                               + "\n, totalBytes: " + totalBytes
                                                               + "\n, fileName: " + fileName + ", appName: " + appName);
        }

        public void onDownloadPause(string placementId, ATCallbackInfo callbackInfo, long totalBytes, long currBytes,
            string fileName, string appName) {
            Debug.Log("wcx Developer onDownloadPause------->" + JsonMapper.ToJson(callbackInfo.toDictionary())
                                                              + "\n, totalBytes: " + totalBytes + ", currBytes:" +
                                                              currBytes
                                                              + "\n, fileName: " + fileName + ", appName: " + appName);
        }

        public void onDownloadStart(string placementId, ATCallbackInfo callbackInfo, long totalBytes, long currBytes,
            string fileName, string appName) {
            Debug.Log("wcx Developer onDownloadStart------->" + JsonMapper.ToJson(callbackInfo.toDictionary())
                                                              + "\n, totalBytes: " + totalBytes + ", currBytes:" +
                                                              currBytes
                                                              + "\n, fileName: " + fileName + ", appName: " + appName);
        }

        public void onDownloadUpdate(string placementId, ATCallbackInfo callbackInfo, long totalBytes, long currBytes,
            string fileName, string appName) {
            Debug.Log("wcx Developer onDownloadUpdate------->" + JsonMapper.ToJson(callbackInfo.toDictionary())
                                                               + "\n, totalBytes: " + totalBytes + ", currBytes:" +
                                                               currBytes
                                                               + "\n, fileName: " + fileName + ", appName: " + appName);
        }

        public void onInstalled(string placementId, ATCallbackInfo callbackInfo, string fileName, string appName) {
            Debug.Log("wcx Developer onInstalled------->" + JsonMapper.ToJson(callbackInfo.toDictionary())
                                                          + "\n, fileName: " + fileName + ", appName: " + appName);
        }
    }
}